package com.speechb.service.impl;

import com.speechb.entity.Menu;
import com.speechb.mapper.MenuMapper;
import com.speechb.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author llj
 * @since 2022-04-20
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    MenuMapper menuMapper;

    @Override
    public List<Menu> menulist() {
        List<Menu> menuList = menuMapper.findMenu();
        if (CollectionUtils.isEmpty(menuList)) {
            return Collections.emptyList();
        }
        return convertMenu(menuList);
    }

    @Override
    public List<Menu> search(String search) {
        return menuMapper.search(search);
    }

    /**
     * 转换菜单，成上下级
     *
     * @param menuList 菜单数据
     * @return 装换后的菜单数据
     */
    public List<Menu> convertMenu(List<Menu> menuList) {
        HashMap<Integer, Menu> menuHashMap = new HashMap<>(menuList.size());
        menuList.forEach(menu ->menuHashMap.put(menu.getId(), menu));
        List<Menu> menus = new LinkedList<>();
        menuList.forEach(menu -> {
            if (menu.getParent_id() == 0) {
                menus.add(menu);
                return;
            }
            Menu parentMenu = menuHashMap.get(menu.getParent_id());
            List<Menu> sonMenus = menuHashMap.get(menu.getParent_id()).getMenuList();
            if (sonMenus == null) {
                sonMenus = new LinkedList<>();
                parentMenu.setMenuList(sonMenus);
            }
            sonMenus.add(menu);
        });
        return menus;
    }

}
